package xmind.generator;

import org.xmind.core.*;

import java.io.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 生成xmind文件
 * @author Arnold Yand
 * @since 2018/7/19
 */
public class XmindGenerator {

  private static String xmind_file = "src/tmp.xmind";

  public XmindGenerator(){}

  private void generate() throws Exception {

    IWorkbookBuilder builder = Core.getWorkbookBuilder();
    IWorkbook workbook = builder.createWorkbook();

    ISheet defSheet = workbook.getPrimarySheet();
    ITopic rootTopic = defSheet.getRootTopic();
    rootTopic.setTitleText("duct_duc");

    generateTopic(workbook);

    workbook.save(xmind_file);
  }

  public static void main(String[] args) throws Exception {
    new XmindGenerator().generate();
    System.out.println("generate successful!!!");
  }

  private void generateTopic(IWorkbook workbook) throws Exception {

    ITopic rootTopic = workbook.getPrimarySheet().getRootTopic();

    ITopic wordTopic = workbook.createTopic();
    wordTopic.setTitleText("单词列表");
    rootTopic.add(wordTopic);

    List<String> allLines = loadContent();
    ITopic subWordTopic = null;
    String word = null;
    String soundmark = null;
    String comment = null;
    String other = null;
    for(String line : allLines){
      word = line.substring(0, line.indexOf(" "));
      soundmark = line.substring(line.indexOf("["), line.indexOf("]") + 1);
      if(line.indexOf("【") > 0){
        comment = line.substring(line.indexOf("]") + 2, line.indexOf("【"));
        other = line.substring( line.indexOf("【"));
      } else {
        comment = line.substring(line.indexOf("]") + 2);
        other = "";
      }
      System.out.printf("word:%s|soundmark:%s|comment:%s|other:%s\n", word, soundmark, comment, other);

      subWordTopic = workbook.createTopic();
      subWordTopic.setTitleText(word);

      Collection<String> labels = new ArrayList<String>();
      labels.add(soundmark);
      labels.add(comment);
      labels.add(other);
      subWordTopic.setLabels(labels);

      wordTopic.add(subWordTopic);
    }
  }

  private List<String> loadContent() throws Exception {
    List<String> allLines = new ArrayList<>();
    String line;
    final InputStream is = XmindGenerator.class.getClassLoader().getResourceAsStream("xmind/content.txt");
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
      while ((line = reader.readLine()) != null) {
        allLines.add(line);
      }
    }

    return allLines;
  }

}
